import React, { useEffect, useState } from "react";
import { Row, Col, Button, Modal, message, Spin } from 'antd';
import { useTranslation } from 'react-i18next';
import { get_user_reward, get_user_daily_reward } from '@/utils/mixin.ts';
import Table from '@/components/rewardTable';
import './Reward.scss';
import prev from '@/assets/photos/prev.png';
import next from '@/assets/photos/next.png';
import round from '@/assets/photos/round.png';
import { main } from '@/utils/eth'
export default () => {
    const [spinning, setSpinning] = React.useState(false);
    const [rewardTableData, setRewardTableData] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const { t } = useTranslation();
    const [currentPage, setCurrentPage] = useState(1);
    const pageSize = 10; // 你希望每页显示的数据数量
    const [total, setTotal] = useState(100);

    const onGetM = () => {
        // setIsModalOpen(true);
        setSpinning(true);
        main().then(res => {
            console.log(res)
            message.success('提取成功')
            setSpinning(false);
            fetchData();
        }).catch(err => {
            console.log(err)
            message.error('提取错误')
            setSpinning(false);
        })
    };

    const onCancel = () => {
        setIsModalOpen(false);
    };

    const dateTab = (dateString) => {
        const dateObject = new Date(dateString.updated_date);
        const year = dateObject.getFullYear();
        const month = String(dateObject.getMonth() + 1).padStart(2, '0');
        const day = String(dateObject.getDate()).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`;
        return formattedDate;
    };

    const handlePageChange = (newPage) => {
        setCurrentPage(newPage, () => {
            fetchData()
        });
    };

    const handlePrevPage = () => {
        if (currentPage > 1) {
            handlePageChange(currentPage - 1);
        }
    };
    
    const handleNextPage = () => {
        const totalPages = Math.ceil(total / pageSize);
        console.log(totalPages)
        if (currentPage < totalPages) {
            handlePageChange(currentPage + 1);
        }
    };

    const columns = [
        {
            title: t('日期'),
            dataIndex: 'updated_date',
            render: (text, record) => <span>{dateTab(text)}</span>
        },
        { title: t('代币'), dataIndex: 'currency', key: 'currency' },
        { title: t('平台奖励'), dataIndex: 'share_reward', key: 'share_reward' },
        { title: t('推荐奖励'), dataIndex: 'refer_reward', key: 'refer_reward' },
        { title: t('NFT奖励'), dataIndex: 'nft_reward', key: 'nft_reward' },
    ];

    const [reward, setReward] = useState([]);

    const fetchData = async () => {
        try {
            const res = await get_user_reward({ email: localStorage.getItem('email') });
            setReward(res.data);

            const res1 = await get_user_daily_reward({
                email: localStorage.getItem('email'),
                currency: 'BNB',
                page: currentPage,
                size: pageSize
            });

            setRewardTableData(res1.data);
            setTotal(res1.total); // 设置总数据数量
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    };

    useEffect(() => {
        fetchData(); // 组件挂载时执行一次
    }, [currentPage]); 

    return (
        <>
        <Spin spinning={spinning} fullscreen />
            <Row justify="space-around" className="rewardContent" wrap={false} style={{ marginBottom: '20px' }}>
            <Col span={8} xs={8} sm={8} className="col reward-item">
                    <div>
                        <h3 className="title">{t('总奖励BNB')}</h3>
                        <h3 className="num">{reward.length ? reward[0].total_reward : '0.00'}</h3>
                    </div>
                </Col>
                <Col
                    span={8}
                    xs={8}
                    sm={8}
                    className="col reward-item"
                    style={{ position: 'relative', margin: '0 8px' }}>
                    <h3 className="title">{t('可领取奖励BNB')}</h3>
                    <div
                        style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-around'
                        }}>
                        <h3 className="num">{reward.length ? reward[0].available_reward : '0.00'}</h3>
                        <div style={{ flex: 1, display: 'flex', justifyContent: 'end' }}>
                            <div className="getBtn" onClick={() => {onGetM(reward.length ? reward[0].available_reward : '0.00')}}>
                                {t('Get')}
                            </div>
                        </div>
                    </div>
                </Col>
                <Col span={8} xs={8} sm={8} className="reward-item">
                    <h3 className="title">{t('已领取奖励BNB')}</h3>
                    <h3 className="num">{reward.length ? reward[0].total_withdraw : '0.00'}</h3>
                </Col>
            </Row>
            <div className="tableContent" style={{ borderRadius: '20px' }}>
                <Table
                    columns={columns}
                    dataSource={rewardTableData}
                    style={{ borderRadius: '20px' }}
                />
                <Row
                    justify="end"
                    align="middle"
                    style={{
                        margin: "12px 0",
                        marginRight: "25px",
                        marginTop: "-30px"
                    }}
                    
                    >
                    <span onClick={() => {handlePrevPage()}} className="pageBtn">
                    <img src={prev} style={{height: '15px'}} className="round" />
                    {/* <img src={prev} className="prev" /> */}
                    </span>
                    <h3
                        style={{
                        fontSize: "14px",
                        fontWeight: 700,
                        color: "rgba(238, 117, 52, 1)",
                        margin: "0 8px",
                        }}
                        
                    >
                        {currentPage*1 < 10 ? '0' + currentPage : currentPage}页
                    </h3>
                    <span onClick={() => {handleNextPage()}} className="pageBtn">
                    <img src={next} style={{height: '15px'}} className="round" />
                    {/* <img src={next} className="next" /> */}
                    </span>
              </Row>
            </div>

            

            <Modal
                closable={false}
                open={isModalOpen}
                onCancel={onCancel}
                cancelText={t('Cancel')}
                okText={t('Confirm')}
                footer={() => (
                    <>
                        <Button onClick={onCancel}>{t('Cancel')}</Button>
                        <Button style={{ background: 'rgba(238, 117, 52, 1)', color: 'white' }}>
                            {t('Confirm')}
                        </Button>
                    </>
                )}>
                <p className="modal-content">{t('Confirm withdrawal of rewards?')}</p>
            </Modal>
        </>
    );
};
